// pages/user_quickread/quickread.js

var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //最高学历列表
    educationList: ['请选择最高学历','小学', '初中', '高中', '高职', '中专', '中技', '高技', '专科', '本科', '硕士', '博士', '其他'],
    //选择的学历索引
    eduIndex: 0,
    //专业列表
    professList: [],
    //选择的专业索引
    professIndex: 0,
    //是否禁用按钮
    disabled: false,
    //姓名
    name: '',
    //手机号码
    phone: '',
    //选择内容的文字颜色
    text_color: ['#8B8B8B', '#8B8B8B', '#8B8B8B'],
    //身份证号码
    idcard: '',
    //福利券列表
    policy_info: [{
      "local_policy_id": "0",
      "policy_name": "请选择",
      "policy_id": "0",
      "policy_amount": 200,
      "number": "15",
      "used_number": "0",
      "start_time": "",
      "end_time": "",
      "explain": "",
      "surplus_number": 0,
      "key": "请选择"
    }],
    //选择的福利券索引
    policyIndex: 0,
    logo: '',
    isShowGetUserInfo: false
  },

  //姓名监听
  nameChange(e) {
    var reg = new RegExp(/[~\!\@\#\$\%\^\&\*\(\)\_\+\-\=\,\.\?\<\>]/g)
    this.setData({
      'name': e.detail.value.replace(reg, "")
    });
  },

  //手机号码监听
  phoneChange(e) {
    this.setData({
      'phone': e.detail.value
    });
  },

  //身份证监听
  idcardChange(e) {
    this.setData({
      'idcard': e.detail.value
    });
  },

  /**
   * 学历监听
   */
  bindEduChange(e) {
    if (e.detail.value == '0'){
      this.setData({
        'text_color[0]': '#8B8B8B'
      })
    }else{
      this.setData({
        'text_color[0]': '#333333'
      })
    }

    this.setData({
      'eduIndex': e.detail.value
    })
  },

  /**
   * 专业监听
   */
  bindProfessChange(e) {
    if (e.detail.value == '0') {
      this.setData({
        'text_color[1]': '#8B8B8B'
      })
    } else {
      this.setData({
        'text_color[1]': '#333333'
      })
    }

    this.setData({
      'professIndex': e.detail.value
    })
  },

  //优惠政策监听
  bindTicketChange(e) {
    if (e.detail.value == '0') {
      this.setData({
        'text_color[2]': '#8B8B8B'
      })
    } else {
      this.setData({
        'text_color[2]': '#333333'
      })
    }

    this.setData({
      'policyIndex': e.detail.value
    })
  },

  submit(e) {
    if (!this.data.name) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
      return;
    }
    if (!/^1[356789][0-9]{9}$/.test(this.data.phone)) {
      wx.showToast({
        title: '请输入正确的手机号码',
        icon: 'none'
      });
      return;
    }
    if (this.data.idcard.length != 18 && this.data.idcard.length != 15) {
      wx.showToast({
        title: '请输入正确的身份证号码',
        icon: 'none'
      });
      return;
    }

    if (parseInt(this.data.eduIndex) == 0) {
      wx.showToast({
        title: '请选择学历',
        icon: 'none'
      });
      return;
    }

    if (this.data.professList[this.data.professIndex]['product_id'] == 0) {
      wx.showToast({
        title: '请选择课程',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '拼命加载中...',
      icon: 'none'
    });
    wx.request({
      url: `${app.globalData.url}c=order&m=replacedEnrolment`,
      method: 'post',
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        user_id: wx.getStorageSync('user_id'),
        name: this.data.name,
        phone: this.data.phone,
        id_card: this.data.idcard,
        education: parseInt(this.data.eduIndex),
        product_id: this.data.professList[this.data.professIndex]['product_id'],
        local_policy_id: this.data.policy_info[this.data.policyIndex] ? this.data.policy_info[this.data.policyIndex]['local_policy_id'] : 0
      },
      success: res => {
        wx.hideLoading();
        res = res.data;
        if (res.status == 200) {
          wx.navigateTo({
            url: '/pages/guidanceStudy/payment/payment?orderId=' + res.data.order_sn,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          });
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      policy_info: [{
        "local_policy_id": "0",
        "policy_name": "请选择福利券(非必选)",
        "policy_id": "0",
        "policy_amount": 200,
        "number": "15",
        "used_number": "0",
        "start_time": "",
        "end_time": "",
        "explain": "",
        "surplus_number": 0,
        "key": "请选择福利券(非必选)"
      }]
    })
    wx.showLoading({
      title: '拼命加载中...',
      icon: 'none'
    });
    if (wx.getStorageSync('user_id')) {
      wx.request({
        url: app.globalData.url + 'c=order&m=index&user_id=' + wx.getStorageSync('user_id'),
        success: res => {
          wx.hideLoading();
          res = res.data;
          if (res.status == 200) {
            res.data.policy_info.map(item => {
              item['key'] = item['policy_name'] + "(" + item['surplus_number'] + "张)";
            });
            var policy_info = this.data.policy_info;
            policy_info.push(...res.data.policy_info);

            //添加请选择选项
            var new_list = res.data.professional_info ;
            new_list.unshift({
              'product_id': 0,
              'product_name': '请选择报读专业'
            }) ;

            this.setData({
              'professList': new_list,
              'policy_info': policy_info,
              'logo': res.data.user_info.logo
            });
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none'
            });
          }
        }
      });
    }else{
      this.getSetting();
    }
  },

  //授权获取个人头像和昵称
  getUserInfo(e) {
    if (e.detail.userInfo) {
      this.setData({
        'isShowGetUserInfo': false
      })
      wx.setStorageSync('wx_head', e.detail.userInfo.avatarUrl);
      wx.setStorageSync('wx_name', e.detail.userInfo.nickName);
      wx.login({
        success: res => {
          wx.setStorageSync('code', res.code);
          this.parseUnionID(e.detail.encryptedData, e.detail.iv);
        }
      })
      wx.showToast({
        title: '获取个人信息成功',
        icon: 'none'
      });
    } else {
      wx.showToast({
        title: '个人信息授权失败',
        icon: 'none'
      });
      wx.redirectTo({
        url: 'pages/guidanceStudy/fuli/fuli'
      });
    }
  },
  //授权
  getSetting() {
    wx.getSetting({
      success: res => {
        //没授权过
        if (!res.authSetting['scope.userInfo']) {
          wx.hideLoading();
          this.setData({
            isShowGetUserInfo: true
          })
        } else {
          this.isRegister(wx.getStorageSync('union_id'));
        }
      }
    })
  },
  /**
   * 解析unionID
   */
  parseUnionID(encryptedData, iv) {
    wx.showLoading({
      title: '拼命加载中...',
    });
    wx.request({
      url: app.globalData.url + 'c=home&m=getPhoneNumber',
      data: {
        'encryptedData': encryptedData,
        'iv': iv,
        'code': wx.getStorageSync('code')
      },
      success: (res) => {
        res = res.data;
        if (res.status == 200) {
          //保存unionID到本地
          // var phone = res.data.purePhoneNumber;
          var union_id = res.data.unionId;
          wx.setStorageSync('union_id', union_id);
          this.isRegister(union_id);
        } else {
          wx.showToast({
            title: '获取个人信息失败，请重试',
            icon: 'none'
          })
          this.setData({
            getPhoneNumberChange: true
          })
        }
      }
    })
  },
  //判断unionID是否注册
  isRegister(union_id) {
    wx.request({
      url: app.globalData.url + 'c=user&m=isRegister',
      data: {
        union_id: union_id
      },
      success: res => {
        wx.hideLoading();
        res = res.data;
        if (res.status == 200) {
          if (res.data.is_register != 0) {
            //已注册
            wx.setStorageSync('user_id', res.data.user_id);
            app.globalData.userId = res.data.user_id;
            wx.request({
              url: app.globalData.url + 'c=order&m=index&user_id=' + wx.getStorageSync('user_id'),
              data: {
                user_id: wx.getStorageSync('user_id'),
              },
              success: res => {
                res = res.data;
                if (res.status === 200) {
                  res.data.policy_info.map(item => {
                    item['key'] = item['policy_name'] + "(" + item['surplus_number'] + "张)";
                  });
                  var policy_info = this.data.policy_info;
                  policy_info.push(...res.data.policy_info);
                  this.setData({
                    'professList': res.data.professional_info,
                    'policy_info': policy_info,
                    'logo': res.data.user_info.logo
                  });
                  //上传头像和手机号码
                  wx.request({
                    url: app.globalData.url + 'c=user&m=keepWeChat',
                    data: {
                      user_id: res.data.id,
                      wx_head: wx.getStorageSync('wx_head'),
                      wx_name: wx.getStorageSync('wx_name')
                    },
                    success: res => {
                      wx.hideLoading();
                      res = res.data;
                    }
                  })
                } else {
                  wx.showToast({
                    title: res.msg,
                    icon: 'none'
                  })
                }
              }
            });
          } else {
            wx.redirectTo({
              url: '/pages/welcome/applydesc/applydesc'
            });
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          });
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})